# -*- coding:utf-8 -*-
# __author__ : "张百科"
# Date: 2021/1/25 21:42
# File: advise.py
# IDE: PyCharm

from rest_framework.viewsets import GenericViewSet
from serializers.advise import AdviseSerializer
from models.advise import Advise
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from utils.response.response import BaseResponse
from utils.Decorators.webworkdecorator import WorkDecorator
from utils.pagination import pagination,pageSerializer
from rest_framework.decorators import action
from rest_framework.schemas import ManualSchema
from coreapi import Field
import coreschema
import datetime
from utils.response.httpstate import *


class AdviseViewSet(GenericViewSet):

    queryset = Advise.objects.filter(is_delete=0)
    serializer_class = AdviseSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    pagination_class =pagination.Pagination
    search_fields = ('category')

    @WorkDecorator(operate="意见反馈", message='列表')
    def list(self, request,*args,**kwargs):

        queryset = self.filter_queryset(self.get_queryset())
        page_queryset = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_queryset, many=True)
        count = self.paginator.page.paginator.count  # 总数
        num = self.paginator.page.paginator.num_pages  # 页数
        page_size = self.paginator.get_page_size(request)  # 每页显示条数
        pageserializer = pageSerializer.Serializer({'count': count, 'page_num': num, 'page_size': page_size})

        return BaseResponse(data=serializer.data,page=pageserializer.data)

    @WorkDecorator(operate="意见反馈", message='新增')
    def create(self, request, *args, **kwargs):
        data = request.data
        # 2.创建序列化器
        serializer = self.get_serializer(data=data)
        # 3.校验
        serializer.is_valid(raise_exception=True)
        # 4.保存
        serializer.save()
        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="意见反馈", message='回复')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True,location='form', schema=coreschema.Integer(description='意见ID')),
            Field(name='reply', required=True,location='form', schema=coreschema.String(description='回复内容')),
        ])
            )
    def reply(self, request,*args,**kwargs):
        postData = request.data
        print(postData)
        id = postData['id']
        reply = postData['reply']

        advise = Advise.objects.get(id=int(id))
        advise.reply=reply
        advise.reply_time=datetime.datetime.now()
        advise.save()

        # 5.返回响应
        return BaseResponse()

    @WorkDecorator(operate="意见反馈", message='设置是否可见')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='意见ID')),
        ])
            )
    def setPublic(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']

        advises = Advise.objects.filter(id=id, is_delete=0)
        if advises:
            advise = advises[0]
            is_public = advise.is_public
            if is_public == 1:
                advise.is_public = 0
            else:
                advise.is_public = 1
            advise.save()
            # serializer = self.get_serializer(user, many=False)
            return BaseResponse()
        else:
            return BaseResponse(message='未找到数据', code=CODE_BUSSINESS_ERROR)


    @WorkDecorator(operate="意见反馈", message='是否满意')
    @action(methods=['put'], detail=False, schema=ManualSchema(
        fields=[
            Field(name='id', required=True, location='form', schema=coreschema.Integer(description='意见ID')),
        ])
            )
    def setSatisfied(self, request, *args, **kwargs):
        postData = request.data
        id = postData['id']

        advises = Advise.objects.filter(id=id, is_delete=0)
        if advises:
            advise = advises[0]
            is_satisfied = advise.is_satisfied
            if is_satisfied == 1:
                advise.is_satisfied = 0
            else:
                advise.is_satisfied = 1
            advise.save()
            # serializer = self.get_serializer(user, many=False)
            return BaseResponse()
        else:
            return BaseResponse(message='未找到数据', code=CODE_BUSSINESS_ERROR)

    @WorkDecorator(operate="意见反馈", message='详情')
    def retrieve(self, request, pk, *args, **kwargs):

        object = Advise.objects.filter(pk=pk).first()

        object.read_count += 1
        object.save()
        print(object)
        serializer = self.get_serializer(object)
        print(serializer.data)
        # 5.返回响应
        return BaseResponse(data=serializer.data)

    @WorkDecorator(operate="意见反馈", message='删除')
    def destroy(self, request, pk, *args, **kwargs):

        object = Advise.objects.filter(pk=pk).first()
        object.is_delete = 1
        object.save()
        return BaseResponse()